﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LayersDotNet.Entity;
using LayersDotNet.DataAccess.Interface;

namespace LayersDotNet.DataAccess.EntityFx
{
    public class EFInstanceProvider : IDataAccessAccessPoint
    {
        private TestDbEntities _dbContext;

        public EFInstanceProvider()
        {
            _dbContext = new TestDbEntities();
        }

        #region "Object Management"

        private Dictionary<Type, object> _instances = new Dictionary<Type, object>();

        private object GetSharedInstance<T1, T2>() where T2 : class
        {
            if (!_instances.ContainsKey(typeof(T1)))
            {
                _instances[typeof(T1)] = Activator.CreateInstance<T1>();

                (_instances[typeof(T1)] as BaseDA<T2>).EntityContext = _dbContext;
                (_instances[typeof(T1)] as BaseDA<T2>).DataAccess = this;
            }

            return _instances[typeof(T1)];
        }
        
        #endregion

        public void Refresh()
        {
            if (_dbContext.Connection.State != System.Data.ConnectionState.Open)
                _dbContext.Connection.Open();
        }

        public Interface.IBankDA BankDA
        {
            get
            {
                return GetSharedInstance<BankDA, Bank>() as BankDA;
            }
        }

        public Interface.ICustomerDA CustomerDA
        {
            get
            {
                return GetSharedInstance<CustomerDA, Customer>() as CustomerDA;
            }
        }
    }
}
